<template>
  <a-row style="padding: 10px;">
    <a-col span="24">
      <a-form layout="inline">
        <a-form-item label="租户名称">
          <a-input v-model="search.tenantName" placeholder="请输入租户名称！"></a-input>
        </a-form-item>
        <a-form-item label="租户代码">
          <a-input v-model="search.tenantCode" placeholder="请输入租户代码！"></a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="searchList">查询</a-button>
        </a-form-item>
      </a-form>
    </a-col>
    <a-col span="24">
      <a-table :dataSource="data" :columns="columns" :pagination="pagination" :loading="loading" size="small" bordered
               :rowKey="record => record.tenantId">
        <template slot="operation" slot-scope="text, record, index">
          <div>
            <span>
              <a v-if="record.state === 1 || record.state === 0" @click="() => tenantApp(index)">应用信息</a>
              <a v-if="record.state === 1 || record.state === 0" @click="() => updateTenant(index)">编辑</a>
              <a v-if="record.state === 1" @click="() => lockTenant(index)">锁定</a>
              <a v-if="record.state === 2" @click="() => lockTenant(index)">解锁</a>
            </span>
          </div>
        </template>
      </a-table>
      <a-pagination showSizeChanger :pageSize="pageObj.pageSize" :total="pageObj.total" v-model="pageObj.page"
                    :pageSizeOptions="pageObj.pageSizeOptions" style="height: 50px; line-height: 50px;"
                    :showTotal="total => `总计 ${total} 条`" @change="pageChange" @showSizeChange="showSizeChange"/>
    </a-col>
    <a-modal v-model="model.visible" title="修改租户信息">
      <a-form :form="model.form">
        <a-form-item label="租户名称" :label-col="model.labelCol" :wrapper-col="model.wrapperCol">
          <a-input placeholder="请输入租户名称！"
                   v-decorator="['tenantName', {rules: [{ required: true, message: '请输入租户名称！'}]}]"/>
        </a-form-item>
        <a-form-item label="租户代码" :label-col="model.labelCol" :wrapper-col="model.wrapperCol">
          <a-input placeholder="请输入租户代码！"
                   v-decorator="['tenantCode', {rules: [{ required: true, message: '请输入租户代码！'}]}]"/>
        </a-form-item>
        <a-form-item label="租户描述" :label-col="model.labelCol" :wrapper-col="model.wrapperCol">
          <a-input placeholder="请输入租户描述！"
                   v-decorator="['introduce']"/>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button key="submit" type="primary" :loading="model.loading" @click="updateTenantOk">确定</a-button>
        <a-button key="back" @click="handleCancel">取消</a-button>
      </template>
    </a-modal>

    <!-- 租户应用管理 -->
    <a-modal v-model="model.app.visible" title="租户应用管理" width="1200px">
      <a-row>
        <a-col span="8">
          <a-table :dataSource="model.app.showData" :columns="model.app.columns" :loading="model.app.loading"
                   size="small" bordered :rowKey="record => record.appId" :pagination="pagination"
                   :rowSelection="model.app.rowSelection">
            <template slot="operation" slot-scope="text, record, index">
              <div>
                <a v-if="record.tenantAppId != null" @click="() => lockTenantApp(record)">{{record.state === 2 ? '解锁'
                  : '锁定'}}</a>
                <a v-if="record.tenantAppId == null" @click="() => bindTenantApp(index)">开通</a>
              </div>
            </template>
          </a-table>
        </a-col>
        <a-col span="16">
          <a-table :dataSource="model.app.menu.showData" :columns="model.app.menu.columns"
                   size="small" bordered :rowKey="record => record.menuId"
                   :rowSelection="model.app.menu.rowSelection" :pagination="pagination"
                   :defaultExpandAllRows="model.app.menu.defaultExpandAllRows">
            <template slot="operation" slot-scope="text, record, index">
              <div>
                <a v-if="record.tenantMenuId != null" @click="() => lockTenantMenu(record)">{{record.state
                  === 2 ?
                  '解锁'
                  : '锁定'}}</a>
                <a v-if="record.tenantMenuId == null" @click="() => bindTenantMenu(record)">开通</a>
              </div>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </a-modal>
  </a-row>
</template>

<script>
  export default {
    name: 'Tenant',
    data () {
      return {
        pageObj: {total: 10, pageSize: 10, pageNum: 1, pageSizeOptions: ['5', '10', '20', '50', '100']},
        search: {
          tenantName: '',
          tenantCode: ''
        },
        model: {
          labelCol: {span: 7},
          wrapperCol: {span: 12},
          loading: false,
          visible: false,
          title: '修改租户信息',
          form: this.$form.createForm(this),
          data: {},
          app: {
            visible: false,
            loading: false,
            menu: {
              data: [],
              allData: [],
              allDataList: [],
              showData: [],
              selectResourceData: {},
              defaultExpandAllRows: true,
              rowSelection: {
                type: 'checkbox',
                selectedRowKeys: [],
                onChange: this.onChange
              },
              columns: [
                {
                  title: '应用菜单名称',
                  dataIndex: 'menuName',
                  sorter: true
                }, {
                  title: '应用菜单类型',
                  dataIndex: 'menuType',
                  sorter: true,
                  customRender: (text, record, index) => {
                    if (text === 0) {
                      return '分类导航'
                    }
                    if (text === 1) {
                      return '菜单页面'
                    }
                    if (text === 2) {
                      return '查询类按钮'
                    }
                    if (text === 3) {
                      return '操作类按钮'
                    }
                  }
                }, {
                  title: '状态',
                  dataIndex: 'state',
                  sorter: true,
                  customRender: (text, record, index) => {
                    if (record.tenantMenuId == null) {
                      return '未开通'
                    } else {
                      return text === 2 ? '锁定' : '正常'
                    }
                  }
                }, {
                  title: '操作',
                  scopedSlots: {customRender: 'operation'}
                }
              ]
            },
            rowSelection: {
              type: 'radio',
              selectedRowKeys: [],
              onChange: this.appOnChange
            },
            allData: [],
            data: [],
            showData: [],
            tenantData: {},
            selectAppData: {},
            columns: [
              {
                title: '应用名称',
                dataIndex: 'appName',
                sorter: true
              }, {
                title: '状态',
                dataIndex: 'state',
                sorter: true,
                customRender: (text, record, index) => {
                  if (record.tenantAppId == null) {
                    return '未开通'
                  } else {
                    return text === 2 ? '锁定' : '正常'
                  }
                }
              }, {
                title: '操作',
                scopedSlots: {customRender: 'operation'}
              }
            ]
          }
        },
        loading: false,
        data: [],
        pagination: false,
        columns: [
          {
            title: '序号',
            width: '20',
            customRender: (text, record, index) => {
              return index + this.pageObj.pageSize * (this.pageObj.pageNum - 1) + 1
            }
          }, {
            title: '租户名称',
            dataIndex: 'tenantName',
            sorter: true
          }, {
            title: '租户代码',
            dataIndex: 'tenantCode',
            sorter: true
          }, {
            title: '描述',
            dataIndex: 'introduce',
            sorter: true
          }, {
            title: '创建时间',
            dataIndex: 'createTime',
            sorter: true
          }, {
            title: '状态',
            dataIndex: 'state',
            sorter: true,
            customRender: (text, record, index) => {
              return text === 2 ? '锁定' : '正常'
            }
          }, {
            title: '操作',
            fixed: 'right',
            width: 200,
            scopedSlots: {customRender: 'operation'}
          }
        ],
        checkedKeysResult: [],
        checkedKeys: []
      }
    },
    mounted () {
      this.searchList()
      this.http.post('upmsApi', '/app/getAppList', {
        pageSize: -1,
        data: {
          appType: 2
        }
      }).then((res) => {
        if (res.success) {
          this.model.app.allData = res.rows
        }
      })
    },
    methods: {
      // 查询数据
      searchList () {
        this.loading = true
        this.http.post('upmsApi', '/admin/tenant/getTenantList', {
          pageNum: this.pageObj.pageNum,
          pageSize: this.pageObj.pageSize,
          data: {...this.search}
        }).then((res) => {
          if (res.success) {
            this.data = res.rows
            this.pageObj.total = res.total
          }
          this.loading = false
        })
      },
      // 更新租户
      updateTenant (index) {
        this.model.visible = true
        this.model.title = '修改租户信息'
        this.model.data = this.data[index]
        console.log({...this.model.data})
        setTimeout(() => {
          this.model.form.setFieldsValue({
            tenantName: this.model.data.tenantName,
            tenantCode: this.model.data.tenantCode,
            introduce: this.model.data.introduce
          })
        }, 100)
      },
      // 锁定/解锁租户
      lockTenant (index) {
        console.log('锁定租户' + index)
        const that = this
        this.$confirm({
          title: that.data[index].state === 1 ? '锁定租户！?' : '解锁租户！',
          onOk () {
            return new Promise((resolve, reject) => {
              that.http.post('upmsApi', '/admin/admin/lockTenant', {
                tenantId: that.data[index].tenantId,
                state: that.data[index].state === 1 ? 2 : 1
              }).then((res) => {
                if (res.success) {
                  that.$message.info(res.message)
                  that.searchList()
                  resolve(res.message)
                } else {
                  reject(res.message)
                }
              })
            })
          }
        })
      },
      // 租户应用信息
      tenantApp (index) {
        this.model.app.visible = true
        this.model.app.showData = []
        this.model.app.menu.showData = []
        this.model.app.rowSelection.selectedRowKeys = []
        this.model.app.tenantData = this.data[index]
        this.getTenantAppList()
      },
      // 查询租户绑定应用列表
      getTenantAppList () {
        this.http.post('upmsApi', '/admin/tenant/getTenantAppListCache', {
          tenantId: this.model.app.tenantData.tenantId
        }).then((res) => {
          if (res.success) {
            this.model.app.data = res.rows
            let showData = JSON.parse(JSON.stringify(this.model.app.allData))
            showData.forEach(item => {
              this.model.app.data.forEach(item2 => {
                if (item.appId === item2.appId) {
                  item.tenantAppId = item2.tenantAppId
                  item.state = item.state === 2 ? 2 : item2.state
                }
              })
            })
            this.model.app.showData = showData
          }
        })
      },
      // 更新租户
      updateTenantOk (e) {
        e.preventDefault()
        this.model.form.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values)
            this.model.loading = true
            this.http.post('upmsApi', '/admin/tenant/updateTenant', {
              tenantId: this.model.data.tenantId,
              ...values
            }).then((res) => {
              if (res.success) {
                this.$message.info(res.message)
                this.searchList()
              }
              this.model.loading = false
              this.model.visible = false
            })
          }
        })
      },
      // 绑定租户应用
      bindTenantApp (index) {
        this.http.post('upmsApi', '/admin/tenant/bindTenantApp', {
          sourceIds: [this.model.app.tenantData.tenantId],
          targetIds: [this.model.app.showData[index].appId]
        }).then((res) => {
          if (res.success) {
            this.$message.info(res.message)
            this.getTenantAppList()
          }
        })
      },
      // 锁定/解锁应用
      lockTenantApp (record) {
        const that = this
        this.$confirm({
          title: record.state === 2 ? '解锁应用！?' : '锁定应用！',
          onOk () {
            return new Promise((resolve, reject) => {
              that.http.post('upmsApi', '/admin/tenant/lockTenantApp', {
                sourceIds: [record.tenantAppId],
                state: record.state === 2 ? 1 : 2
              }).then((res) => {
                if (res.success) {
                  that.$message.info(res.message)
                  that.getTenantAppList()
                  resolve(res.message)
                } else {
                  reject(res.message)
                }
              })
            })
          }
        })
      },
      // app选择事件
      appOnChange (selectedRowKeys, selectedRows) {
        console.log(selectedRows[0])
        this.model.app.rowSelection.selectedRowKeys = selectedRowKeys
        if (selectedRows[0].state !== 2) {
          this.model.app.selectAppData = selectedRows[0]
          this.http.post('upmsApi', '/app/getMenuTreeByAppId', {
            appId: this.model.app.selectAppData.appId
          }).then((res) => {
            if (res.success) {
              this.model.app.menu.allData = res.rows
              this.handleTree(res.rows)
              this.getMenuList()
            }
          })
        } else {
          this.model.app.menu.showData = []
        }
      },
      // 获取应用菜单列表
      getMenuList () {
        this.http.post('upmsApi', '/admin/tenant/getMenuListByTenantId', {
          tenantId: this.model.app.tenantData.tenantId,
          appId: this.model.app.selectAppData.appId
        }).then((res) => {
          if (res.success) {
            this.model.app.menu.data = res.rows
            let showData = JSON.parse(JSON.stringify(this.model.app.menu.allData))
            this.setAddedResource(showData, this.model.app.menu.data)
            this.model.app.menu.showData = showData
          }
        })
      },
      setAddedResource (allData, exData) {
        allData.forEach(item => {
          exData.forEach(item2 => {
            if (item.menuId === item2.menuId) {
              item.tenantMenuId = item2.tenantMenuId
              item.state = item.state === 2 ? 2 : item2.state
            }
          })
          if (item.children && item.children.length > 0) {
            this.setAddedResource(item.children, exData)
          }
        })
      },
      // 绑定租户应用菜单
      bindTenantMenu (record) {
        let allList = this.model.app.menu.allDataList
        let exList = []
        this.model.app.menu.data.forEach(item => exList.push(item.menuId))
        let checkList = [record.menuId]
        checkList.push(...exList)
        let bindList = this.menuOnChange(checkList, allList, exList).endKeys
        this.http.post('upmsApi', '/admin/tenant/bindTenantMenu', {
          appId: this.model.app.selectAppData.appId,
          sourceIds: [this.model.app.tenantData.tenantId],
          targetIds: bindList
        }).then((res) => {
          if (res.success) {
            this.$message.info(res.message)
            this.getMenuList()
          }
        })
      },
      // 锁定/解锁应用
      lockTenantMenu (record) {
        let sourceIds = []
        if (record.state !== 2) {
          let allList = this.model.app.menu.data
          let allListKeys = []
          let exList = []
          allList.forEach(item => {
            if (item.state !== 2) {
              allListKeys.push(item.menuId)
              if (item.menuId !== record.menuId) {
                exList.push(item.menuId)
              }
            }
          })
          let menuIds = this.menuOnChange(exList, allList, allListKeys).delKeys
          allList.forEach(item => {
            if (menuIds.indexOf(item.menuId) !== -1) {
              sourceIds.push(item.tenantMenuId)
            }
          })
          sourceIds.push(record.tenantMenuId)
        } else {
          let allList = this.model.app.menu.data
          let exList = []
          allList.forEach(item => {
            if (item.state !== 2) {
              exList.push(item.menuId)
            }
          })
          let checkList = [record.menuId]
          checkList.push(...exList)
          let bindList = this.menuOnChange(checkList, allList, exList).endKeys
          allList.forEach(item => {
            if (bindList.indexOf(item.menuId) !== -1) {
              sourceIds.push(item.tenantMenuId)
            }
          })
        }
        const that = this
        this.$confirm({
          title: record.state === 2 ? '解锁应用菜单！?' : '锁定应用菜单！',
          onOk () {
            that.http.post('upmsApi', '/admin/tenant/lockTenantMenu', {
              sourceIds: sourceIds,
              state: record.state === 2 ? 1 : 2
            }).then((res) => {
              if (res.success) {
                that.$message.info(res.message)
                that.getMenuList()
              }
            })
          }
        })
      },
      // 模态框取消
      handleCancel () {
        this.model.visible = false
      },
      handleTree (treeList) {
        treeList.forEach(item => {
          this.model.app.menu.allDataList.push(item)
          if (item.children) {
            this.handleTree(item.children)
          }
        })
      },
      onChange (checkedKeys) {
        let allList = this.model.app.menu.allDataList
        let selectKeys = this.model.app.menu.rowSelection.selectedRowKeys
        this.model.app.menu.rowSelection.selectedRowKeys = this.menuOnChange(checkedKeys, allList, selectKeys).endKeys
      },
      menuOnChange (checkedKeys, allList, selectKeys) {
        let returnData = {
          endKeys: [],
          delKeys: []
        }
        if (checkedKeys.length > selectKeys.length) {
          this.checkedKeys = []
          // 获取所有上级节点
          checkedKeys.forEach(item => this.getParentNode(allList, item))
          // 获取选中的下级几点及所有的上级节点
          this.checkedKeys.push(...checkedKeys)
          // 去重
          const checkedKeysResult = Array.from(new Set(this.checkedKeys))
          returnData.endKeys = checkedKeysResult
          return returnData
        } else {
          let delItem = null
          selectKeys.forEach(item => {
            if (checkedKeys.indexOf(item) === -1) {
              delItem = item
            }
          })
          if (delItem != null) {
            // 查找改节点的所有下级节点
            let childrenList = this.getChildrenList(allList, delItem)
            let endList = []
            let delList = []
            checkedKeys.forEach(item => {
              if (childrenList.indexOf(item) === -1) {
                endList.push(item)
              } else {
                delList.push(item)
              }
            })
            returnData.endKeys = endList
            returnData.delKeys = Array.from(new Set(delList))
            return returnData
          }
        }
      },
      // 获取父级节点
      getParentNode (dataList, parentId) {
        dataList.forEach(item => {
          let id = item.menuId
          if (parentId === id) {
            this.checkedKeys.push(item.menuId)
            if (item.parentId !== 0) {
              this.getParentNode(dataList, item.parentId)
            }
          }
        })
      },
      // 获取下级节点
      getChildrenList (dataList, parentId) {
        let childrens = []
        dataList.forEach(item => {
          let id = item.menuId
          if (parentId === item.parentId) {
            childrens.push(item.menuId)
            childrens.push(...this.getChildrenList(dataList, id))
          }
        })
        return childrens
      },
      // 切换页数
      pageChange (pageNum, pageSize) {
        this.pageObj.pageNum = pageNum
        this.pageObj.pageSize = pageSize
        this.searchList()
      },
      // 切换每页数量
      showSizeChange (current, size) {
        this.pageObj.pageNum = 1
        this.pageObj.pageSize = size
        this.searchList()
      }
    }
  }
</script>

<style scoped>

</style>
